<script setup lang="ts">
import Header from '@/components/Header.vue'
import Menu from '@/components/Menu.vue'
import MyBox from '@/components/MyBox.vue'
import OutputChart from './components/OutputChart.vue'
import Top10Chart from './components/Top10Chart.vue'
import YieldChart from './components/YieldChart.vue'
import SeamlessList from './components/SeamlessList.vue'
import RatioChart from './components/RatioChart.vue'
import { computed, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { useMessage } from '@/hooks/useMessage'
import { Query } from '@/api'
import { onBeforeUnmount } from 'vue'

const { query } = useRoute()
//看板标题
const title = computed(() => {
  return query.label || ''
})

//当日产量及直通率
const data = ref<any[]>([])
const cols = ref<any[]>([])

//刷新周期
const flushTimer = ref()
//底部责任人
const otherInfo = ref({
  PD: '',
  QA: '',
  PE: ''
})

//直通率
const yieldChartInfo = ref({
  legendList: [],
  xList: [],
  yList: []
})
//产量
const outputChartInfo = ref({
  legendList: [],
  timeList: [],
  okList: [],
  ngList: []
})
//Top10
const top10ChartInfo = ref({
  xList: [],
  yList: []
})
//不良占比
const rationChartInfo = ref({
  list: []
})

//线别
const line = ref('')
const lineList = ref()
//产品编号
const poNumber = ref('')
const poList = ref<any[]>([])
//切换线别
const changeLine = async () => {
  //获取责任人信息
  const match = lineList.value.length && lineList.value.filter((item: any)=> item.Value == line.value)
  // otherInfo.value = match.length && match[0]
  poNumber.value = ''
  //关闭定时循环
  stopTimer()
  //获取产品编号信息
  const res = (await Query({
    inputStr: `GroupName=${query.groupName};$;JobType=${query.jobType};$;OperType=GetValue;$;Key=PN;$;Line=${line.value}`
  })) as any
  if (res.code !== 200) {
    message.error(res.msg)
    return
  }
  const { listInfo } = res.data
  poList.value = listInfo || []
}

//获取数据
const getKBInfo = async () => {
  const res = (await Query({
    inputStr: `GroupName=${query.groupName};$;JobType=${query.jobType};$;OperType=GetKBInfo;$;Key=PN;$;Line=${line.value};$;PN=${poNumber.value}`
  })) as any
  if (res.code !== 200) {
    message.error(res.msg)
    return
  }
  const { capaInfo, monthCapaInfo, errInfo, defectInfo,masterInfo } = res.data
  data.value = capaInfo || []
  otherInfo.value = masterInfo.length && masterInfo[0]

  // 格式化图表信息
  yieldChartInfo.value.xList = monthCapaInfo.map((item: any) => item.DateNode)
  yieldChartInfo.value.yList = monthCapaInfo.map((item: any) => item.FPY)

  outputChartInfo.value.timeList = monthCapaInfo.map((item: any) => item.DateNode)
  outputChartInfo.value.okList = monthCapaInfo.map((item: any) => item.OKQty)
  outputChartInfo.value.ngList = monthCapaInfo.map((item: any) => item.NGQty)

  //Top10
  top10ChartInfo.value.xList = errInfo.map((item: any) => item.Descr).reverse() || []
  top10ChartInfo.value.yList = errInfo.map((item: any) => item.Qty).reverse() || []

  //占比
  rationChartInfo.value.list =
    defectInfo.map((item: any) => {
      return {
        value: item.FPY,
        name: item.Descr
      }
    }) || []
}

//切换产品编号
const changePO = async () => {
  // 先关闭定时器再重新启动刷新周期
  stopTimer()
  //选择产品编号之后，开始循环获取数据GetKBInfo
  startTimer()
}

const message = useMessage()
//获取页面信息
const getPageInfo = async () => {
  const res = (await Query({
    inputStr: `GroupName=${query.groupName};$;JobType=${query.jobType};$;OperType=Getpage`
  })) as any
  if (res.code !== 200) {
    message.error(res.msg)
    return
  }
  const { ctInfo, monthlyCapaFieldInfo, defectFieldInfo, capaFieldInfo, lineInfo } = res.data
  cols.value = capaFieldInfo
  //直通率
  const match = monthlyCapaFieldInfo.filter((item: any) => item.value == 'FPY') || []
  yieldChartInfo.value.legendList = match.length && [match[0].label]

  // 30天产量
  const result =
    monthlyCapaFieldInfo.filter((item: any) => item.value == 'OKQty' || item.value == 'NGQty') || []
  outputChartInfo.value.legendList = result.length && result.map((item: any) => item.label)
  //不良Top10
  // top10ChartInfo.value.xList = defectFieldInfo.map((item: any) => item.label)
  //刷新时间
  flushTimer.value = ctInfo.length && ctInfo[0].CT
  lineList.value = lineInfo || []
}

// 1.循环过程中，重新选择【线别】，关闭循环，选定【产品编号】后重新开始
// 2.循环过程中，重新选择【产品编号】，关闭循环并开始新循环

// 定义状态
const isRunning = ref(false)
const timerId = ref<number | null>(null)

// 开始定时器
const startTimer = async () => {
  if (isRunning.value) return // 防止重复启动

  isRunning.value = true
  console.log('定时器启动')

  // 立即执行一次
  await getKBInfo()

  // 设置定时器，每3分钟执行一次 (3分钟 = 3*60*1000 = 180000毫秒)
  const timer = flushTimer.value * 1000
  timerId.value = window.setInterval(getKBInfo, timer)
}

// 停止定时器
const stopTimer = () => {
  if (timerId.value) {
    window.clearInterval(timerId.value)
    timerId.value = null
    isRunning.value = false
    console.log('定时器已停止')
  }
}

// 组件卸载前清理定时器
onBeforeUnmount(() => {
  stopTimer()
})

onMounted(() => getPageInfo())
</script>
<template>
  <div class="w-full overflow-hidden my-page">
    <Header :title="`${title}` + '看板'" />
    <section class="board-content">
      <div class="flex justify-between row">
        <MyBox title="30天产量及直通率" style="width: 65%">
          <template v-slot:main>
            <!-- 直通率 -->
            <YieldChart :data="yieldChartInfo" />
            <!-- 工站产量 -->
            <OutputChart :data="outputChartInfo" />
          </template>
        </MyBox>
        <MyBox title="当月测试不良前10项" style="width: calc(35% - 20px)">
          <template v-slot:main>
            <Top10Chart :data="top10ChartInfo" />
          </template>
        </MyBox>
      </div>
      <div class="flex justify-between row">
        <MyBox title="当日工单直通率" style="width: 65%">
          <template v-slot:main>
            <div style="margin-top: 20px"><SeamlessList :data="data" :cols="cols" /></div>
          </template>
        </MyBox>
        <MyBox
          :title="'不良占比' + `${poNumber ? '_' + poNumber : ''}`"
          style="width: calc(35% - 20px)"
        >
          <template v-slot:extra>
            <div class="flex extra">
              <div class="select-box">
                <el-select
                  v-model="poNumber"
                  style="width: 200px"
                  placeholder="请选择产品编号"
                  @change="changePO"
                >
                  <el-option
                    v-for="(item, index) in poList"
                    :key="index"
                    :label="item.Label"
                    :value="item.Value"
                  />
                </el-select>
              </div>
            </div>
          </template>
          <template v-slot:main>
            <RatioChart :data="rationChartInfo" />
          </template>
        </MyBox>
      </div>
      <div class="flex justify-between other-info">
        <MyBox title="" style="width: 100%">
          <template v-slot:main>
            <div class="flex items-center justify-between">
              <p>
                <el-select
                  v-model="line"
                  style="width: 170px"
                  placeholder="请选择线别"
                  @change="changeLine"
                >
                  <el-option
                    v-for="(item, index) in lineList"
                    :key="index"
                    :label="item.Label"
                    :value="item.Value"
                  />
                </el-select>
              </p>
              <p>生产责任人：{{ otherInfo.PD ?? '' }}</p>
              <p>质量责任人：{{ otherInfo.QA ?? '' }}</p>
              <p>工程责任人：{{ otherInfo.PE ?? '' }}</p>
            </div>
          </template>
        </MyBox>
      </div>
    </section>
    <Menu />
  </div>
</template>
<style lang="less" scoped>
.row {
  margin: 15px auto;
}

.extra {
  position: absolute;
  right: 20px;
  top: 15px;
  font-size: 22px;
  color: #8fe1ff;
}

.other-info {
  color: #8fe1ff;
  font-size: 24px;
  .flex {
    width: 98%;
    margin: 0 auto;
  }
}
.el-select-dropdown__item {
  font-size: 18px;
}
</style>
